#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>

using namespace std;

#define PATHNAME "."
#define PROJ_ID 0x11
#define SHM_SIZE 4096
//获取key值
key_t Get_key()
{
    int key = ftok(PATHNAME, PROJ_ID);
    if(key == -1)
    {
        cerr << errno << ":" << strerror(errno) << endl;
        exit(1);
    }
    printf("key值获取成功 key: %d\n", key);
    return key;
}

int GetShmHelper(key_t k, int flags)
{
    int shm_id = shmget(k, SHM_SIZE, flags);
    if(shm_id == -1)
    {
        cerr << errno << ":" << strerror(errno) << endl;
        exit(2);
    }
    printf("shm_id获取成功 shm_id: %d\n", shm_id);
    return shm_id;
}

//获取shm_id
int Get_Shm(key_t k)
{
    return GetShmHelper(k, IPC_CREAT);
}

int Create_Shm(key_t k)
{
    return GetShmHelper(k, IPC_CREAT | IPC_EXCL | 0600);
}

//接触shm资源
void* At_Shm(const int shm_id)
{
    void* ret = shmat(shm_id, nullptr, 0);
    if((long long)ret == -1)
    {
        cerr << errno << ":" << strerror(errno) << endl;
    }
    return ret;
}

//回收shm资源
void detach_Shm(void* start)
{
    shmdt(start);
}

//销毁shm资源
void Del_Shm(int shm_id)
{
    if(shmctl(shm_id, IPC_RMID, nullptr) == -1)
    {
        cerr << errno << ":" << strerror(errno) << endl;
    }
    printf("shm资源销毁成功\n");
}
